package instantHelper.Raceway;

import instantHelper.Models.CustomHttpClient;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class Contact extends Activity {
	private Person user;
	DbHelper myDbHelper;
	private String TAG = Contact.class.getSimpleName();
	private boolean isedit = false;
	private String IMEI = "";
	private String macAddress;
	public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds

	/** Single instance of our HttpClient */
	private static HttpClient mHttpClient;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.contact);
		// To fill edit box is user saved before his info
		setEditBox();
		// To get imei address
		TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		IMEI = telephonyManager.getDeviceId();

	}

	private void setEditBox() {

		String androidId;
		Person person = selectUserById();
		// cursor bind user info

		Log.d(TAG, "person in cursor=" + person.toString());
		// To receive editboxes
		if (!person.equals(null)) {
			EditText etName = (EditText) findViewById(R.id.etName);
			EditText etSurname = (EditText) findViewById(R.id.etSurname);
			EditText etPhone = (EditText) findViewById(R.id.etPhoneNumber);
			EditText etEmail = (EditText) findViewById(R.id.etEmail);
			EditText etAddress = (EditText) findViewById(R.id.etAddress);
			EditText etTcNo = (EditText) findViewById(R.id.etTcNo);
			EditText etuserNick = (EditText) findViewById(R.id.etUserNick);
			EditText etuserPassword = (EditText) findViewById(R.id.etUserPassword);

			// Set Editboxes that you got from databases
			etName.setText(person.getName());
			etSurname.setText(person.getSurname());
			etAddress.setText(person.getAddress());
			etEmail.setText(person.geteMail());
			etPhone.setText(person.getPhoneNumber());
			etTcNo.setText(person.getTCNo());
			etuserNick.setText(person.getUserNick());
			etuserPassword.setText(person.getUserPassword());
		}

	}

	public Person selectUserById() {
		myDbHelper = new DbHelper(Contact.this);
		SQLiteDatabase db = myDbHelper.getReadableDatabase();
		Cursor cursor = null;
		Person person = new Person();
		// Get the database and run the query
		String selection = InstantHelperConstant.DB_COLUMN_ID + "=1";
		try {
			cursor = db.query(InstantHelperConstant.DB_PERSON_TABLE, null,
					selection, null, null, null, null, null);
			Log.d(TAG, "in Cursor =" + cursor.toString());
			startManagingCursor(cursor);

		} catch (Exception e) {
			Log.d(TAG, "select query something wrong (IGNORE THIS)");
			// TODO: handle exception
		}
		while (cursor.moveToNext()) {
			isedit = true;
			person.setAddress(cursor.getString(2));
			person.seteMail(cursor.getString(3));
			person.setName(cursor.getString(4));
			person.setPhoneNumber(cursor.getString(5));
			person.setSurname(cursor.getString(6));
			person.setTCNo(cursor.getString(7));
			person.setUserNick(cursor.getString(8));
			person.setUserPassword(cursor.getString(9));

		}
		myDbHelper.close();
		db.close();
		cursor.close();
		return person;
	}

	// When save button clicked
	public void onClickBtnSave(View button) throws IllegalStateException,
			IOException, URISyntaxException {

		boolean validation = true;
		boolean isContinue = true;
		EditText etName = (EditText) findViewById(R.id.etName);
		EditText etSurname = (EditText) findViewById(R.id.etSurname);
		EditText etPhone = (EditText) findViewById(R.id.etPhoneNumber);
		EditText etEmail = (EditText) findViewById(R.id.etEmail);
		EditText etAddress = (EditText) findViewById(R.id.etAddress);
		EditText etTcNo = (EditText) findViewById(R.id.etTcNo);
		EditText etUserNick = (EditText) findViewById(R.id.etUserNick);
		EditText etUserPassword = (EditText) findViewById(R.id.etUserPassword);
		user = new Person();
		user.setName(etName.getText().toString());
		user.setSurname(etSurname.getText().toString());
		user.setAddress(etAddress.getText().toString());
		user.seteMail(etEmail.getText().toString());
		user.setPhoneNumber(etPhone.getText().toString());
		user.setTCNo(etTcNo.getText().toString());
		user.setUserNick(etUserNick.getText().toString());
		user.setUserPassword(etUserPassword.getText().toString());
		// Unique android id
		String androidId = Secure.getString(getBaseContext()
				.getContentResolver(), Secure.ANDROID_ID);
		Pattern numberPattern = Pattern.compile("[0-9]*");
		if ((user.getUserNick().equalsIgnoreCase("") || user.getUserPassword()
				.equalsIgnoreCase(""))) {
			isContinue = false;
			Toast.makeText(this, " Fill UserNick And UserPassword",
					Toast.LENGTH_LONG).show();
			etPhone.focusSearch(etPhone.FOCUS_DOWN);
		}
		// argument to matcher is string to validate
		Matcher matcher = numberPattern.matcher(user.getTCNo());
		if (!matcher.matches()) // on Success
		{
			// invalid
			// pop up ERROR message
			Toast.makeText(this, " Invalid TC Number", Toast.LENGTH_LONG)
					.show();
			validation = false;
			etPhone.focusSearch(etTcNo.FOCUS_DOWN);

		}

		matcher = numberPattern.matcher(user.getPhoneNumber());

		if (!matcher.matches()) // on Success
		{
			// invalid
			// pop up ERROR message
			Toast.makeText(this, " Invalid phone number", Toast.LENGTH_LONG)
					.show();
			validation = false;
			etPhone.focusSearch(etPhone.FOCUS_DOWN);

		}

		// create contentValues for Db insert
		ContentValues contentValues = new ContentValues();
		contentValues.put(InstantHelperConstant.DB_COLUMN_ADDRESS,
				user.getAddress());
		contentValues
				.put(InstantHelperConstant.DB_COLUMN_ANDROID_ID, androidId);
		contentValues.put(InstantHelperConstant.DB_COLUMN_EMAIL,
				user.geteMail());
		contentValues.put(InstantHelperConstant.DB_COLUMN_NAME, user.getName());
		contentValues.put(InstantHelperConstant.DB_COLUMN_PHONE,
				user.getPhoneNumber());
		contentValues.put(InstantHelperConstant.DB_COLUMN_SURNAME,
				user.getSurname());
		contentValues.put(InstantHelperConstant.DB_COLUMN_TC, user.getTCNo());
		contentValues.put(InstantHelperConstant.DB_COLUMN_USER_NICK,
				user.getUserNick());
		contentValues.put(InstantHelperConstant.DB_COLUMN_USER_PASSWORD,
				user.getUserPassword());
		if (isContinue) {
			if (isedit == true) {
				Person oldPerson = selectUserById();
				if (updatePersonToCentralAPP(androidId, user, oldPerson)
						.equalsIgnoreCase("successfull"))
					updatePerson(contentValues);

			} else {
				String res = sendPersonToCentralAPP(androidId, user);
				if (res.equalsIgnoreCase("successfull"))
					savePerson(contentValues);

			}
		}
	}

	private String updatePersonToCentralAPP(String androidId, Person user2,
			Person oldPerson) {
		String url = InstantHelperConstant.CentralAppURL
				+ "/androidhelprequest/updatePhoneInfo";

		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("userAddress", user
				.getAddress()));
		postParameters.add(new BasicNameValuePair("androidId", androidId));
		postParameters
				.add(new BasicNameValuePair("userEmail", user.geteMail()));
		postParameters.add(new BasicNameValuePair("userName", user.getName()));
		postParameters.add(new BasicNameValuePair("userTel", user
				.getPhoneNumber()));
		postParameters.add(new BasicNameValuePair("userSurname", user
				.getSurname()));
		postParameters.add(new BasicNameValuePair("userTCNo", user.getTCNo()));
		postParameters.add(new BasicNameValuePair("userNick", user
				.getUserNick()));
		postParameters.add(new BasicNameValuePair("IMEI", IMEI));
		postParameters.add(new BasicNameValuePair("userPassword", user
				.getUserPassword()));
		postParameters.add(new BasicNameValuePair("oldUserPassword", oldPerson
				.getUserPassword()));
		postParameters.add(new BasicNameValuePair("oldUserNick", oldPerson
				.getUserNick()));
		String response = null;
		String result = "";
		try {
			response = CustomHttpClient.executeHttpPost(url, postParameters);
			String res = response.toString();
			JSONObject jObject = new JSONObject(res);
			result = jObject.getString("result");
			Context context = getApplicationContext();
			CharSequence text = "Saccessfully Updated in Center App";
			int duration = Toast.LENGTH_SHORT;
			if (!result.equalsIgnoreCase("successfull"))
				text = result;
			Toast toast = Toast.makeText(context, text, duration);
			toast.show();

		} catch (Exception e) {

		}
		return result;

	}

	private String sendPersonToCentralAPP(String androidId, Person user2)
			throws IllegalStateException, IOException, URISyntaxException {
		String url = InstantHelperConstant.CentralAppURL
				+ "/androidhelprequest/newPhoneInfo";

		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("userAddress", user
				.getAddress()));
		postParameters.add(new BasicNameValuePair("androidId", androidId));
		postParameters
				.add(new BasicNameValuePair("userEmail", user.geteMail()));
		postParameters.add(new BasicNameValuePair("userName", user.getName()));
		postParameters.add(new BasicNameValuePair("userTel", user
				.getPhoneNumber()));
		postParameters.add(new BasicNameValuePair("userSurname", user
				.getSurname()));
		postParameters.add(new BasicNameValuePair("userTCNo", user.getTCNo()));
		postParameters.add(new BasicNameValuePair("IMEI", IMEI));
		postParameters.add(new BasicNameValuePair("userNick", user
				.getUserNick()));
		postParameters.add(new BasicNameValuePair("userPassword", user
				.getUserPassword()));
		String response = null;
		String result = "";
		try {
			response = CustomHttpClient.executeHttpPost(url, postParameters);
			String res = response.toString();
			JSONObject jObject = new JSONObject(res);
			result = jObject.getString("result");
			Context context = getApplicationContext();
			CharSequence text = "Saccessfully saved in Center App";
			int duration = Toast.LENGTH_SHORT;
			if (!result.equalsIgnoreCase("successfull"))
				text = result;
			Toast toast = Toast.makeText(context, text, duration);
			toast.show();

		} catch (Exception e) {

		}
		return result;
	}

	private void updatePerson(ContentValues contentValues) {

		myDbHelper = new DbHelper(Contact.this);
		SQLiteDatabase db = myDbHelper.getWritableDatabase();
		try {
			String whereClause = InstantHelperConstant.DB_COLUMN_ID + "='1'";
			db.update(InstantHelperConstant.DB_PERSON_TABLE, contentValues,
					whereClause, null);

		} catch (Exception e) {
			Log.d(TAG, "an error when updating user info");
		}
		Log.d(TAG, "succesfully updated");
		myDbHelper.close();
		db.close();
		Context context = getApplicationContext();
		CharSequence text = "Saccessfully Updated by Mobile Application";
		int duration = Toast.LENGTH_SHORT;

		Toast toast = Toast.makeText(context, text, duration);
		toast.show();

	}

	public void savePerson(ContentValues contentValues) {

		myDbHelper = new DbHelper(Contact.this);
		SQLiteDatabase db = myDbHelper.getWritableDatabase();

		try {
			db.insertOrThrow(InstantHelperConstant.DB_PERSON_TABLE, null,
					contentValues);

		} catch (Exception e) {
			// TODO: handle exception
		}

		Log.d(TAG,
				String.format("Insert %s table values User values ==%s ",
						InstantHelperConstant.DB_PERSON_TABLE,
						contentValues.toString()));

		myDbHelper.close();
		db.close();
		isedit = true;
		Context context = getApplicationContext();
		CharSequence text = "Saccessfully saved by Mobile App";
		int duration = Toast.LENGTH_SHORT;
		Toast toast = Toast.makeText(context, text, duration);
		toast.show();

	}

	// When cancel button clicked
	public void onClickBtnCancel(View button) {
		finish();
	}

}
